﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Xml.Linq;
using System.Web.UI.HtmlControls;

namespace Framework
{
    public partial class Search : System.Web.UI.Page
    {
        public DGSFrameworkEntities entity = new DGSFrameworkEntities();

        public List<udv_Categories> allCate = new List<udv_Categories>();
        public List<udv_Articles> allArt = new List<udv_Articles>();
        public List<udv_Products> allPro = new List<udv_Products>();

        public List<udv_Articles> lstArticleSearch = new List<udv_Articles>();

        protected void Page_Load(object sender, EventArgs e)
        {
            Form.DefaultButton = btnSearchAdvanced.UniqueID;

            if (!IsPostBack)
            {
                LoadCacheCategory();
                LoadCacheArticle();
                LoadCacheProduct();

                LoadSearch();
            }
        }

        public void LoadCacheCategory()
        {
            if (Cache["Category"] == null)
            {
                Cache["Category"] = allCate = entity.udv_Categories.ToList();
            }
            else
            {
                allCate = (List<udv_Categories>)Cache["Category"];
            }
        }

        public void LoadCacheArticle()
        {
            if (Cache["Article"] == null)
            {
                Cache["Article"] = allArt = entity.udv_Articles.Include("udv_Categories").ToList();
            }
            else
            {
                allArt = (List<udv_Articles>)Cache["Article"];
            }
        }

        public void LoadCacheProduct()
        {
            if (Cache["Product"] == null)
            {
                Cache["Product"] = allPro = entity.udv_Products.Include("udv_Categories").ToList();
            }
            else
            {
                allPro = (List<udv_Products>)Cache["Product"];
            }
        }

        public string GetDefaultTitlePage()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));

            XElement xEInfomationConfigWebsite = xDocInfo.Descendants("ConfigWebsite").FirstOrDefault();
            return xEInfomationConfigWebsite.Element("Title").Value.Trim();
        }

        public string GetDefaultMetaDescription()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));

            XElement xEInfomationConfigWebsite = xDocInfo.Descendants("ConfigWebsite").FirstOrDefault();
            return xEInfomationConfigWebsite.Element("MetaDescription").Value.Trim();
        }

        public string GetDefaultMetaKeyword()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));

            XElement xEInfomationConfigWebsite = xDocInfo.Descendants("ConfigWebsite").FirstOrDefault();
            return xEInfomationConfigWebsite.Element("MetaKeywords").Value.Trim();
        }

        public string GetDefaultMetaTitle()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));

            XElement xEInfomationConfigWebsite = xDocInfo.Descendants("ConfigWebsite").FirstOrDefault();
            return xEInfomationConfigWebsite.Element("MetaTitle").Value.Trim();
        }

        public void AddTag(string metaDescription, string metaKeywords, string metaTitle, string pageTitle)
        {
            if (string.IsNullOrEmpty(metaDescription))
            {
                metaDescription = GetDefaultMetaDescription();
            }
            if (string.IsNullOrEmpty(metaKeywords))
            {
                metaKeywords = GetDefaultMetaKeyword();
            }
            if (string.IsNullOrEmpty(pageTitle))
            {
                pageTitle = GetDefaultTitlePage();
            }
            if (string.IsNullOrEmpty(metaTitle))
            {
                metaTitle = GetDefaultMetaTitle();
            }
            HtmlHead headTag = (HtmlHead)this.Master.FindControl("Head1");
            headTag.Title = pageTitle;
            HtmlMeta PagemetaTag = new HtmlMeta();
            PagemetaTag.Name = "description";
            PagemetaTag.Content = metaDescription;
            headTag.Controls.AddAt(2, PagemetaTag);
            PagemetaTag = new HtmlMeta();
            PagemetaTag.Name = "keywords";
            PagemetaTag.Content = metaKeywords;
            headTag.Controls.AddAt(3, PagemetaTag);
            PagemetaTag = new HtmlMeta();
            PagemetaTag.Name = "title";
            PagemetaTag.Content = metaTitle;
            headTag.Controls.AddAt(4, PagemetaTag);
        }

        public void LoadSearch()
        {
            if (Request.QueryString["Keyword"] != null)
            {
                txtSearchAdvanced.Text = Server.UrlDecode(Request.QueryString["keyword"].ToString());
                string keyword = Server.UrlDecode(Globals.RemoveSign4VietnameseString(Request.QueryString["keyword"].ToString()));
                AllSearch(keyword);
                aProduct.HRef = ResolveUrl("~/" + DGSFramework.Globals.GetUrl("tim-kiem-san-pham/" + Server.UrlEncode(txtSearchAdvanced.Text), "SearchGame.aspx?Keyword=" + Server.UrlEncode(txtSearchAdvanced.Text)));
                AddTag("Tổng hợp tin về bài viết " + txtSearchAdvanced.Text,
                    txtSearchAdvanced.Text,
                    "Tìm kiếm bài viết: " + txtSearchAdvanced.Text,
                    "Tìm kiếm bài viết: " + txtSearchAdvanced.Text);
            }
            else
            {
                Response.Redirect(ResolveUrl("~/" + Globals.GetUrl("Errors", "Errors.aspx")));
            }
        }

        private void AllSearch(string keyword)
        {

            lstArticleSearch = allArt.FindAll(delegate(udv_Articles math)
            {
                if (Globals.RemoveSign4VietnameseString(math.Title.ToLower()).Contains(keyword.ToLower()) && math.IsApproved == true && ((math.ReleaseDate != null && math.ExpireDate != null) ? (math.ReleaseDate <= DateTime.Now && math.ExpireDate >= DateTime.Now) : ((math.ReleaseDate <= DateTime.Now || math.ExpireDate >= DateTime.Now) || (math.ReleaseDate == null && math.ExpireDate == null))))
                    return true;
                else
                    return false;
            });
            lstArticleSearch = lstArticleSearch.OrderByDescending(ls => ls.AddedDate).ToList();

            //paging
            double NOProducts = 0;
            int pageSize = 6;
            object objPage = Request.QueryString["page"];
            if (objPage != null)
            {
                int pageindex;
                if (int.TryParse(objPage.ToString(), out pageindex))
                {
                    PagingControl1.PageIndex = pageindex;
                }
            }
            else
            {
                PagingControl1.PageIndex = 1;
            }
            PagingControl1.pageUrl = ResolveUrl("~/" + Globals.GetUrl("tim-kiem/" + keyword, "Search.aspx?Keyword=" + keyword));
            NOProducts = (double)lstArticleSearch.Count() / pageSize;
            char splitChar = '.';

            if (NOProducts.ToString().Contains('.'))
            { NOProducts++; splitChar = '.'; }

            if (NOProducts.ToString().Contains(','))
            { NOProducts++; splitChar = ','; }

            PagingControl1.TotalPage = int.Parse(NOProducts.ToString().Split(splitChar).GetValue(0).ToString());

            if (PagingControl1.TotalPage <= 1)
                PagingControl1.Visible = false;
            else
                PagingControl1.Visible = true;
            var s = lstArticleSearch.Skip((PagingControl1.PageIndex - 1) * pageSize).Take(pageSize);
            rpArticle.DataSource = s;
            rpArticle.DataBind();
        }

        protected void btnSearchAdvanced_Click(object sender, EventArgs e)
        {
            string textSearch = txtSearchAdvanced.Text.Trim();

            Response.Redirect(ResolveUrl("~/" + DGSFramework.Globals.GetUrl("tim-kiem/" + Server.UrlEncode(textSearch), "SearchArticle.aspx?Keyword=" + Server.UrlEncode(textSearch))));
        }
    }
}